/**
 * @description 触摸控制
 */
define(['jquery', 'eventer', 'browser'], function($, eventer, browser){
	var toucher = {
		build : function(opts){
			var $this = $(opts.el), touching = false, start_x, start_y, end_x, end_y;

			//按下绑定
			$this.on(eventer.events.down, function(e){
				touching = true;
				if(opts.startStop){
					e.preventDefault();
				}
				if(browser.versions.mobile){
					start_x = e.originalEvent.targetTouches[0].clientX;
					start_y = e.originalEvent.targetTouches[0].clientY;
				}else{
					start_x = e.clientX + document.body.scrollLeft + document.documentElement.scrollLeft;
					start_y = e.clientY + document.body.scrollTop + document.documentElement.scrollTop;
				}
				end_x = start_x;
				end_y = start_y;

				if(typeof opts.ontouchstart === 'function'){
					opts.ontouchstart.call(this, e, start_x, start_y);
				}

				//非移动端禁止默认行为
				if(!browser.versions.mobile){
					return false;
				}
			});

			//滑动绑定
			$this.on(eventer.events.move, function(e){
				if(opts.moveStop) e.preventDefault(); //阻止触摸时浏览器的缩放、滚动条滚动等
				if(browser.versions.mobile){
					end_x = e.originalEvent.targetTouches[0].clientX;
					end_y = e.originalEvent.targetTouches[0].clientY;
				}else{
					end_x = e.clientX + document.body.scrollLeft + document.documentElement.scrollLeft;
					end_y = e.clientY + document.body.scrollTop + document.documentElement.scrollTop;
				}
				if(typeof opts.ontouchmove === 'function' && touching){
					opts.ontouchmove.call(this, e, start_x, start_y, end_x, end_y);
				}

				//非移动端禁止默认行为
				if(!browser.versions.mobile){
					return false;
				}
			});

			//抬起绑定
			$this.on(eventer.events.up, function(e){
				if(opts.endStop) e.preventDefault();
				if(/touch/i.test(eventer.events.move) || touching){
					touching = false;
					if(typeof opts.ontouchend === 'function'){
						opts.ontouchend.call(this, e, start_x, start_y, end_x, end_y);
					}
				}
			});

			//取消绑定
			$this.on(eventer.events.cancel, function(e){
				if(opts.cancelStop) e.preventDefault();
				if(/touch/i.test(eventer.events.cancel) || touching) {
					touching = false;
					if (typeof opts.ontouchcancel == 'function'){
						opts.ontouchcancel.call(this, e, start_x, start_y, end_x, end_y);
					}
				}
			});

			//非移动端禁止默认行为
			if(!browser.versions.mobile){
				$this.on(eventer.events.click, function(e){
					if(start_x === end_x && start_y === end_y){
						return true;
					}
					return false;
				});
			}
		}
	};

	return toucher;
});